package cn.idietrade.idietradegoodsorder8003.demo.service.impl;

import cn.idietrade.common.pojo.SecondGoods;
import cn.idietrade.common.pojo.SecondOrder;
import cn.idietrade.common.utils.DateUtil;
import cn.idietrade.common.utils.EmptyUtils;
import cn.idietrade.common.utils.ReturnResultData;
import cn.idietrade.common.utils.SecondOrderPage;
import cn.idietrade.idietradegoodsorder8003.demo.mapper.GoodsOrderMapper;
import cn.idietrade.idietradegoodsorder8003.demo.mapper.OrderMapper;
import cn.idietrade.idietradegoodsorder8003.demo.service.OrderGoodsService;
import cn.idietrade.idietradegoodsorder8003.demo.service.OrderService;
import cn.idietrade.idietradegoodsorder8003.demo.utils.DynamicAmountCalculation;
import cn.idietrade.idietradegoodsorder8003.demo.utils.RedisUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


@Service
public class CreateOrderServiceImpl implements OrderService {

    @Resource
    private DynamicAmountCalculation dynamicAmountCalculation;
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private GoodsOrderMapper goodsOrderMapper;
    @Resource
    private RedisUtil redisUtil;

    @Resource
    private OrderGoodsService orderGoodsService;

    @Override
    public ReturnResultData createOrder(List<SecondOrder> orderList) {
        ReturnResultData resultData = new ReturnResultData();

        if (EmptyUtils.isEmpty(orderList)){
            resultData.setCode(-1);
            resultData.setMessage("数据异常请与管理员联系，商品id传值为null");
            resultData.setData(null);
            return resultData;
        }
        int num = orderMapper.insertOrder(orderList);
        if (num > 0){
            resultData.setCode(1);
            resultData.setMessage("订单生已生成");
            resultData.setData(num);
            return resultData;
        }else {
            resultData.setCode(-1);
            resultData.setMessage("订单插入失败");
            resultData.setData(num);
            return resultData;
        }
    }

    @Override
    public ReturnResultData createOrderRedis(Integer buyerId,String goodsId,Integer goodsNum) {
        ReturnResultData resultData = new ReturnResultData();
        SimpleDateFormat formatter =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(System.currentTimeMillis());
        String nowDate = formatter.format(date);
        if (EmptyUtils.isEmpty(goodsId) | EmptyUtils.isEmpty(buyerId)){
            resultData.setCode(-1);
            resultData.setMessage("数据异常请与管理员联系，商品id或买方id传值为null");
            resultData.setData(null);
            return resultData;
        }
        String[] goodsIds = goodsId.split(",");
        List<Integer> goodsIdList = new ArrayList<>();
        for (String ids : goodsIds) {
            goodsIdList.add(Integer.valueOf(ids));
        }
        List<SecondGoods> goodsInfo = goodsOrderMapper.selectGoodsInfo(goodsIdList);

        List<Float> price = new ArrayList<>();      //单个商品价钱的集合
        String goodsNums = "0";
        for (SecondGoods goods : goodsInfo) {
            price.add(dynamicAmountCalculation.cheng(goods.getPrice(),goodsNum));        //单个商品金额与数量的计算
            //goodsNums = dynamicAmountCalculation.jia(goodsNums,(goods.getGoodsNum()).toString()).toString();   //计算整个订单的商品的数量
        }
        Float totalMoney = (float)0;    //整个订单的总价钱
        for (int i = 0; i<price.size(); i++) {
            totalMoney = dynamicAmountCalculation.jia(totalMoney.toString(),(price.get(i)).toString());     //整个账单商品金额的总和
        }
        List<SecondOrder> orderList = new ArrayList<>();                     //多个商品存入账单，通过list和sqlforeach进行批量插入
        Integer orderNo = (int)Math.floor((Math.random()*1000000)+1);       //生成账单编号

        int end = goodsNums.indexOf(".");       //截取float的“.”及后面的值
        if (end != -1){
            goodsNums = goodsNums.substring(0,end);
        }
        Integer key = orderMapper.selectOrderNums();
        for (SecondGoods goods : goodsInfo) {
            SecondOrder order = new SecondOrder();
            order.setId(++key);
            order.setOrderNo("DDJY"+orderNo);
            order.setBuyerId(buyerId);     //买
            order.setSellerId(goods.getUserId());    //卖家
            order.setTotalPrice(totalMoney);
            order.setGoodsNum(goodsNum);
            order.setGoodsId(goods.getId());
            order.setCreationTime(nowDate);
            orderList.add(order);
        }
        int time = 60*60*24;        //设置过期时间
        key = orderMapper.selectOrderNums();
        for (SecondOrder order : orderList) {
            String value = JSON.toJSONString(order);
            redisUtil.setStr(buyerId.toString(),value,Long.valueOf(time));
        }
            resultData.setCode(1);
            resultData.setMessage("订单生已生成");
            resultData.setData(null);
            return resultData;
    }

    @Override
    public ReturnResultData removeOrderGoodsInfo(Integer goodsId) {
        ReturnResultData resultData = new ReturnResultData();
        if (EmptyUtils.isEmpty(goodsId)) {
            resultData.setCode(-1);
            resultData.setMessage("数据异常请与管理员联系，goodsId传入值为空");
            resultData.setData(null);
            return resultData;
        }
        int num = orderMapper.delOrderGoodsInfo(goodsId);
        if (num > 0){
            resultData.setCode(1);
            resultData.setMessage("订单取消成功");
            resultData.setData(num);
            return resultData;
        }
        resultData.setCode(-1);
        resultData.setMessage("取消订单出现异常，请与管理员联系，数据库删除失败");
        resultData.setData(num);
        return resultData;
    }

    @Override
    public ReturnResultData updateOrderState(Integer orderState,String orderNo) {
        ReturnResultData resultData = new ReturnResultData();
        if (EmptyUtils.isEmpty(orderState) | EmptyUtils.isEmpty(orderNo)) {
            resultData.setCode(-1);
            resultData.setMessage("数据异常请与管理员联系，orderState或orderNo传入值为空");
            resultData.setData(null);
            return resultData;
        }
        int num = orderMapper.updateOrderState(orderState,orderNo);
        if (num > 0){
            resultData.setCode(1);
            resultData.setMessage("订单支付状态成功");
            resultData.setData(num);
            return resultData;
        }
        resultData.setCode(-1);
        resultData.setMessage("修改订单支付状态出现异常，请与管理员联系，数据库修改失败");
        resultData.setData(num);
        return resultData;
    }

    @Override
    public SecondOrder queryRedisLSOrder(Integer userId) {
        SecondOrder secondOrder = JSONObject.parseObject(redisUtil.getStr(userId.toString()), SecondOrder.class);
        return secondOrder;
    }

    @Override
    public boolean deleteRedisLSOrder(Integer userId) {
        try {
            redisUtil.del(userId.toString());
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public int selectOrderNums() {
        return orderMapper.selectOrderNums();
    }

    @Override
    public int addOrder(SecondOrder secondOrder,String goodsIds,String nums) {
        //创建待支付订单
        int i = orderMapper.addOrder(secondOrder);

        int orderMaxId = this.selectOrderNums();
        //向中间表生成数据
        int i1 = orderGoodsService.addOrderGoods(orderMaxId, secondOrder.getBuyerId(), goodsIds, nums);
        if(i>0&&i1>0){
            return 1;
        }
        return 0;
    }

    @Override
    public SecondOrderPage querySecondOrders(Integer pageNum, Integer pageSize, Integer userId) {
        if(pageNum==null||pageNum<=1){
            pageNum=1;
        }
        if(pageSize==null){
            pageSize=3;
        }
        List<SecondOrder> orderList = orderMapper.querySecondOrders(userId);

        SecondOrderPage secondOrderPage = new SecondOrderPage();

        //总数
        int total = orderList.size();
        //总页数
        int pageSum = total % pageSize == 0 ? total / pageSize : total / pageSize + 1;

        //分页
        List<SecondOrder> subList = orderList.stream().skip((pageNum - 1) * pageSize).limit(pageSize).
                collect(Collectors.toList());
        secondOrderPage.setTotal(total);
        secondOrderPage.setList(subList);
        return secondOrderPage;

    }

    @Override
    public int queryOrderId(String orderNo) {
        return orderMapper.queryOrderId(orderNo);
    }

    @Override
    public int updateOrState(Integer orderId, Integer orderState) {
        return orderMapper.updateOrState(orderId,orderState);
    }
}
